<?php

//获取星期方法
function  get_week($date){
    //强制转换日期格式
    $date_str=date('Y-m-d',strtotime($date));
     
    //封装成数组
    $arr=explode("-", $date_str);

    //参数赋值
    //年
    $year=$arr[0];

    //月，输出2位整型，不够2位右对齐
    $month=sprintf('%02d',$arr[1]);

    //日，输出2位整型，不够2位右对齐
    $day=sprintf('%02d',$arr[2]);

    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;

    //转换成时间戳
    $strap = mktime($hour,$minute,$second,$month,$day,$year);

    //获取数字型星期几
    $number_wk=date("w",$strap);

    //自定义星期数组
    $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");

    //获取数字对应的星期
    return $weekArr[$number_wk];
}


/**
 * @param $str
 * $arr 数组
 * $vs  数组的字段
 * $num 读取字符长度
 * $star截取位置
 * @return mixed
 */
function tihuan($arr,$vs,$num,$star){
    foreach ($arr as $k=>$v){
        $str = cut_tags_html($v["$vs"]);
        $cd = cn_substr($str,$num,$star);
        $arr[$k]["$vs"] = $cd;
    }
    return $arr;
}


/**
 * 专题页新闻和栏目
 * $pid 顶级栏目id
 * $lt 分页个数
 */
function m_u($pid,$lt){
    $menu_obj = D("articles_category");
    $news_obj = D("articles");
    $menu = $menu_obj->where("parent_id={$pid}")->select();
    $news_arr = array();
    foreach ($menu as $k=>$v){
        $arr = $news_obj->where("cat_id = {$v['id']} AND is_del=0")->limit($lt)->order("id desc")->select();
        foreach ($arr as $k=>$v){
            $news_arr[] = $arr[$k];
        }
    }
    return $news_arr;
}

/**
 * 截取中文字符串
 * @param string $string 中文字符串
 * @param int $sublen 截取长度
 * @param int $start 开始长度 默认0
 * @param string $code 编码方式 默认UTF-8
 * @param string $omitted 末尾省略符 默认...
 * @return string
 */
function cut_str($string, $sublen = 100, $start = 0, $code = 'UTF-8', $omitted = '...')
{
	$omitted = $omitted ? $omitted : '...';
    if($code == 'UTF-8')
    {
        $pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);
        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)).$omitted;
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = ''; for($i=0; $i<$strlen; $i++)
    {
        if($i>=$start && $i<($start+$sublen))
        {
            if(ord(substr($string, $i, 1))>129)
            {
                $tmpstr.= mb_substr($string, $i, 2);
            }
            else
            {
                $tmpstr.= mb_substr($string, $i, 1);
            }
        }
        if(ord(substr($string, $i, 1))>129) $i++;
    }
        if(strlen($tmpstr)<$strlen ) $tmpstr.= $omitted;
        return $tmpstr;
    }
}

/************* 以上为后期添加方法 ****************/

function md($var,$type=1){
	header("Content-type: text/html; charset=utf-8");
	echo '<pre>';
	//var_dump($var);
	print_r($var);
	echo '</pre>';
	if($type){
		exit;
	}

}
//初始化mem
function init_memcached(){
        S(array(
            'type'=>'memcache',
            'host'=>'127.0.0.1',
            'port'=>'11211',
            'prefix'=>'think',
            )
         ); 
}


function removeXSS($val)
{
	static $obj = null;
	if($obj === null)
	{
		require('./Public/mypurifier/HTMLPurifier.includes.php');
		$config = HTMLPurifier_Config::createDefault();
		$config->set('HTML.TargetBlank', TRUE);
		$obj = new HTMLPurifier($config);  
	}
	return $obj->purify($val);  
}


function uploadOne($imgName, $dirName, $thumb = array())
{
	if(isset($_FILES[$imgName]) && $_FILES[$imgName]['error'] == 0)
	{
		$rootPath = C('IMG_rootPath');
		$upload = new \Think\Upload(array(
			'rootPath' => $rootPath,
		));
		$upload->maxSize = (int)C('IMG_maxSize') * 1024 * 1024;// 设置附件上传大小
		$upload->exts = C('IMG_exts');// 设置附件上传类型
		$upload->savePath = $dirName . '/'; // 图片二级目录的名称
		$info   =   $upload->upload(array($imgName=>$_FILES[$imgName]));
		if(!$info)
		{
			return array(
				'ok' => 0,
				'error' => $upload->getError(),
			);
		}
		else
		{
			$ret['ok'] = 1;
		    $ret['images'][0] = $logoName = $info[$imgName]['savepath'] . $info[$imgName]['savename'];
		    if($thumb)
		    {
		    	$image = new \Think\Image();
		    	foreach ($thumb as $k => $v)
		    	{
		    		$ret['images'][$k+1] = $info[$imgName]['savepath'] . 'thumb_'.$k.'_' .$info[$imgName]['savename'];
				    $image->open($rootPath.$logoName);
				    $image->thumb($v[0], $v[1])->save($rootPath.$ret['images'][$k+1]);
		    	}
		    }
		    return $ret;
		}
	}
}

function showImage($url, $width='', $height='')
{
	if(empty($url))
		return ;
	$url = $url;
	if($width)
		$width = "width='$width'";
	if($height)
		$height = "height='$height'";
	echo "<img src='$url' $width $width />";
}
// 删除图片
function deleteImage($images)
{
	$rp = C('IMG_rootPath');
	foreach ($images as $v)
	{
		$v = str_replace('/uploadfile/', '', $v);
		@unlink($rp . $v);
	}
}

// 判断批量上传的数组中有没有上传至少一张图片
function hasImage($imgName)
{
	foreach ($_FILES[$imgName]['error'] as $v)
	{
		if($v == 0)
			return TRUE;
	}
	return FALSE;
}

  function getMyWeek($type){
  	  $data = array();
	  $w = date('w');
	  $type = empty($type)?0:$type;
  	  if($w ==0){
		  $w1 = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1+7*($type-1),date("Y")));
		  $w2 = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7+7*($type-1),date("Y")));
	  }else{
		  $w1 = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1+7*$type,date("Y")));
		  $w2 = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7+7*$type,date("Y")));
	  }
	
	  $data[] = $w1;
	  $data[] = $w2;
	  return $data;  
  }

 
function getWeek($time){//1491062400
	$weekarray=array("日","一","二","三","四","五","六"); 
    return  "星期".$weekarray[date("w",$time)];
}



function excelTime($date, $time = false) {
	if (function_exists('GregorianToJD')) {
		if (is_numeric($date)) {
			$jd = GregorianToJD(1, 1, 1970);
			$gregorian = JDToGregorian($jd + intval($date) - 25569);
			$date = explode('/', $gregorian);
			$date_str = str_pad($date[2], 4, '0', STR_PAD_LEFT) . "-" . str_pad($date[0], 2, '0', STR_PAD_LEFT) . "-" . str_pad($date[1], 2, '0', STR_PAD_LEFT) . ($time ? " 00:00:00" : '');
			return $date_str;
		}
	} else {
		$date = $date > 25568 ? $date + 1 : 25569;
		$ofs = (70 * 365 + 17 + 2) * 86400;
		$date = date("Y-m-d", ($date * 86400) - $ofs) . ($time ? " 00:00:00" : '');
	}
	return $date;
}

//字符截取
function cn_substr($str, $length, $start=0)
{
	if(strlen($str) < $start+1)
	{
		return '';
	}
	preg_match_all("/./su", $str, $ar);
	$str = '';
	$tstr = '';

	//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
	for($i=0; isset($ar[0][$i]); $i++)
	{
		if(strlen($tstr) < $start)
		{
			$tstr .= $ar[0][$i];
		}
		else
		{
			if(strlen($str) < $length + strlen($ar[0][$i]) )
			{
				$str .= $ar[0][$i];
			}
			else
			{
				break;
			}
		}
	}
	return $str;
}


function cut_tags_html($str)
{
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
			"'<[\/\!]*?[^<>]*?>'si",           // 去掉 HTML 标记
			"'([\r\n])[\s]+'",                 // 去掉空白字符
			"'&(quot|#34);'i",                 // 替换 HTML 实体
			"'&(amp|#38);'i",
			"'&(lt|#60);'i",
			"'&(gt|#62);'i",
			"'&(nbsp|#160);'i",
			"'&(iexcl|#161);'i",
			"'&(cent|#162);'i",
			"'&(pound|#163);'i",
			"'&(copy|#169);'i",
			"'peihuo\.cn|peihuo\.mobi|div|\/'",
			"'&#(\d+);'e");                    // 作为 PHP 代码运行

	$replace = array ("",
			"",
			" ",//"\\1",
			"\"",
			"&",
			"<",
			">",
			" ",
			chr(161),
			chr(162),
			chr(163),
			chr(169),
			"",
			"chr(\\1)");
	return  preg_replace ($search, $replace, $str);
}





 /** 
 * 中文分词处理方法 
 *+--------------------------------- 
 * @param stirng  $string 要处理的字符串 
 * @param boolers $sort=false 根据value进行倒序 
 * @param Numbers $top=0 返回指定数量，默认返回全部 
 *+--------------------------------- 
 * @return void 
 */  
function scws($text, $top = 10, $return_array = false, $sep = ',') {  
    include('./Public/pscws4/pscws4.php'); 
    $cws = new pscws4('utf-8');  
    $cws -> set_charset('utf-8');  
    $cws -> set_dict('./Public/pscws4/etc/dict.utf8.xdb');  
    $cws -> set_rule('./Public/pscws4/etc/rules.utf8.ini');  
    //$cws->set_multi(3);  
    $cws -> set_ignore(true);  
    //$cws->set_debug(true);  
    //$cws->set_duality(true);  
    $cws -> send_text($text);  
    $ret = $cws -> get_tops($top, 'r,v,p');  
    $result = null;  
    foreach ($ret as $value) {  
        if (false === $return_array) {  
            $result .= $sep . $value['word'];  
        } else {  
            $result[] = $value['word'];  
        }  
    }  
    return false === $return_array ? substr($result, 1) : $result;  
} 




function seo_str($sk,$sd){
		$seo['seo_keyword'] = scws($sk);
		if(empty($seo['seo_keyword']))  $seo['seo_keyword'] = C('SEO_STR');
		$seo['seo_description'] = cut_tags_html($sd);
		$seo['seo_description'] = empty($seo['seo_description'])? C('SEO_STR'):cn_substr($seo['seo_description'],250);
		return $seo;
}

//ip地址
 function getCity($ip = ''){
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));   
        if((string)$ip->code=='1'){
           return false;
        }
        $data = (array)$ip->data;
    }
    
    return $data;   
}

//获取查询的字符串
function getQueryStr(){
	 $query_str = $_SERVER['QUERY_STRING'];
     return $query_str;
}

	function getCurSeason($type=1){
		    $season = ceil((date('n'))/3);
		    if($type==1){
		    	$data[] = date('Y-m-d', mktime(0, 0, 0,$season*3-3+1,1,date('Y')));
		        $data[] = date('Y-m-d', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'))); 
		    }else{
		    	$data[] = date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y')));
		        $data[] = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));
		    }	  
		    return $data;
	}

	function getSomeMonths($num){
		$data = array();
		for ($i=0;$i<$num;$i++){
		  $data[] =  date('Y-m',strtotime('-'.$i.' month'));
		}
		return $data;
	}


    //获取开始和结束时间
	function begin_end_month($ym){//年 月
		$ym = empty($ym)?date('Y-m'):$ym;
		$ym = explode('-',$ym);
		$days = cal_days_in_month(CAL_GREGORIAN, $ym[1], $ym[0]);
	    //$days = date('t', strtotime("2011-4-1"));
		//获取起始时间戳和结束时间戳
		$data[]=mktime(0,0,0,date($ym[1]),1,date($ym[0]));//开始
		$data[]=mktime(23,59,59,date($ym[1]),$days,$ym[0]);
		return $data;
	}

	

	function pc_mobile(){
		$res = array('PC','手机');
		return $res;
	}

	function time_life($type,$is_now){
		$data = array();
		if($type=='day'){
			if($is_now==1){
				$data[] = strtotime(date('Y-m-d').'00:00:00');
				$data[] = strtotime(date('Y-m-d').'23:59:59');
			}else{
				$data[] = strtotime(date("Y-m-d",strtotime("-1 day")).'00:00:00');
				$data[] = strtotime(date("Y-m-d",strtotime("-1 day")).'23:59:59');
			}
			
		}elseif($type=='month'){
			if($is_now==1){
				$data[] = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y"))));
				$data[] = strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y"))));
			}else{//上一个月
				$data[] = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y"))));
				$data[] = strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y"))));
			}
			
		}
		return $data;	
	}

	
	function get_threemonths_ago(){
		$data['end']=date("Y-m-d");           
		$days=90; //月份 (转为天数)
		$data['start']=date("Y-m-d",(strtotime($data['end'])-$days*84600));
		return $data;
	}

	//两个月以前
	function get_twomonths_ago(){
		$data['end']=date("Y-m-d");           
		$days=60; //月份 (转为天数)
		$data['start']=date("Y-m-d",(strtotime($data['end'])-$days*84600));
		return $data;
	}

	function is_runyear($year){
		$year = (int)$year;
		if (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100 !== 0))) {  
			return array(false,$year);
		}    
		return  array(true,$year);
	}

	function year_stamp($year){
		$data[]=strtotime($year.'-01-01 00:00:00');
		$data[]= strtotime($year.'-12-31 23:59:59');
		return $data;
	}

	function day_stamp($year,$month,$day){
		$data[]=strtotime($year.'-'.$month.'-'.$day.' 00:00:00');
		$data[]= strtotime($year.'-'.$month.'-'.$day.' 23:59:59');
		return $data;
	}

	function load_cached($type='memcache',$host='127.0.0.1',$port='11211'){
	     S(array(
			'type' => $type,//redis,mongo
			'host' => $host,
			'port' => $port,
		));
	}

	function trim_citys($province,$city){
		$data = array();
		if(strpos($province, '省') !== false){
			$province = rtrim($province, "省") ; 
		}elseif(strpos($province, '市')!== false){
			$province = rtrim($province, "市") ; 
		}

		if(strpos($city, '市') !== false){
			$city = rtrim($city, "市") ; 
		}
		$data['province'] = $province;
		$data['city'] = $city;
		return $data;
	}

//隐藏名字
function hide_name($username){
	$strlen     = mb_strlen($username, 'utf-8');
    $firstStr     = mb_substr($username, 0, 1, 'utf-8');
    $lastStr     = mb_substr($username, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($username, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}

//隐藏手机号
function hide_phone($phone){
	$IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}

function get_encoding($data,$to){
   $encode_arr=array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
   $encoded=mb_detect_encoding($data, $encode_arr);
   $data = mb_convert_encoding($data,$to,$encoded);
   return $data;
}